package ev.data;//need to add this line

import java.util.*;

public class Individual implements Comparable{

	private int[] chromosome;
	private double quality;


	public Individual(int cityNum) {
		this.chromosome = new int[cityNum];
		ArrayList<Integer> list = new ArrayList<Integer>();
		for(int i=0; i<cityNum; i++) {
			list.add(i+1);
		}

		Collections.shuffle(list);
		for(int i=0; i<cityNum; i++) {
			this.chromosome[i] = list.get(i);
		}
		this.calcualteQuality(MyData.getCityData());
	}

	public Individual(int[] cityArray) {

		this.chromosome = cityArray;
		this.calcualteQuality(MyData.getCityData());

	}


	public void calcualteQuality(ArrayList<City> cities) {

		double distance = 0;
		double TotalDistance = 0;
		double xtmp = 0;
		double ytmp = 0;
		City tmp,lastcity,finalcity;
		lastcity = cities.get(chromosome[0]-1);
		finalcity = lastcity;

		for(int i = 1; i < cities.size(); i++){
			tmp = cities.get(chromosome[i]-1);
			xtmp = Math.abs(tmp.getX()-lastcity.getX());
			double xsquare = xtmp*xtmp;
			ytmp = Math.abs(tmp.getY()-lastcity.getY());
			double ysquare = ytmp*ytmp;
			distance = Math.sqrt(xsquare+ysquare);
			TotalDistance += distance;
			lastcity = tmp;
		}

		xtmp = Math.abs(finalcity.getX()-lastcity.getX());
		double xsquare = xtmp*xtmp;
		ytmp = Math.abs(finalcity.getY()-lastcity.getY());
		double ysquare = ytmp*ytmp;
		distance = Math.sqrt(xsquare+ysquare);
		TotalDistance += distance;
		//must add this distance, the travel from last city to the started city

		this.quality = TotalDistance;
	}

	public double getQuality(){
		return this.quality;
	}

	public void setList(int[] chromosome) {
		this.chromosome = chromosome;
	}

	public int[] getList() {
		return this.chromosome;
	}

	public int getCityId(int position){
		return chromosome[position];
	}

	public int compareTo(Object o) {
		Individual p = (Individual) o ;
		if(this.quality > p.quality)
			return 1;
		else if (this.quality == p.quality)
			return 0;
		else
			return -1;
	}
	public Individual copy()
	{
		Individual toReturn = new Individual(this.chromosome.clone());
		return toReturn;
	}
	@Override
	public boolean equals(Object obj) {
		// TODO Auto-generated method stub
		Individual old = (Individual)obj;
		int[] oldChromosome = old.getList();
		for(int i=0; i<this.chromosome.length; i++)
		{
			if(chromosome[i] != oldChromosome[i])
			{
				return false;
			}
		}
		return true;
	}

	@Override
	public int hashCode() {
		// TODO Auto-generated method stub
		String hash = "";
		for(int i=0; i<this.chromosome.length; i++)
		{
			hash += chromosome[i];
		}

		return hash.hashCode();
	}

	public  String  toString()
	{
		String  s="";

		for(int tmp: chromosome)
		{
			s+=tmp + ", ";
		}

		return  s;
	}

}
